package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcAppUserOldmanBindMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcAppUserOldmanBind;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.service.DmcRpcService;
import com.csun.cmny.provider.service.OldmanService;
import com.csun.cmny.provider.service.OmcAppUserOldmanBindService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class OmcAppUserOldmanBindServiceImpl extends BaseService<OmcAppUserOldmanBind> implements OmcAppUserOldmanBindService {

    @Resource
    private OmcAppUserOldmanBindMapper omcAppUserOldmanBindMapper;

    @Resource
    private OldmanService oldmanService;

    @Resource
    private DmcRpcService dmcRpcService;

    @Override
    public Integer userRemovesOldman(Long oldmanId, LoginAuthDto loginAuthDto) {

        OmcAppUserOldmanBind obQuery = new OmcAppUserOldmanBind();
        obQuery.setOldmanId(oldmanId);
        obQuery = omcAppUserOldmanBindMapper.selectOne(obQuery);
        if(obQuery != null && obQuery.getUserId().equals(loginAuthDto.getUserId())){
            Oldman oldmanQuery = new Oldman();
            oldmanQuery.setOldmanId(oldmanId.intValue());
            oldmanQuery = oldmanService.selectByOld(oldmanQuery);
            //如果老人身份证为空，删除该条老人数据
            if(oldmanQuery != null){
                if((oldmanQuery.getOldIdCard() == null || oldmanQuery.getOldIdCard().equals("")) && oldmanQuery.getRemark() == null){
                    oldmanService.deleteByOldId(oldmanId.intValue());
                }
            }
            //解除老人绑定的设备
            int breakRet = dmcRpcService.breakBindDeviceByOldmanId(oldmanQuery.getOldmanId().longValue());
            //解除绑定关系
            return delete(obQuery);
        }else{
            throw new OmcBizException(ErrorCodeEnum.OMC10060004);
        }
    }

    @Override
    public void checkOldmanHasBound(Long oldmanId,LoginAuthDto loginAuthDto) {

        OmcAppUserOldmanBind obQuery = new OmcAppUserOldmanBind();
        obQuery.setOldmanId(oldmanId);
        int ret = selectCount(obQuery);
        if(ret > 0){
            throw new OmcBizException(ErrorCodeEnum.OMC10060005);
        }
    }


}
